import loadScriptJs from "load-script"

const scripts = {
  d3v3: `/C/lib/d3.v3.js` //此地址为线上相对路径地址，本地调试时 改为本地引用路径
}

export const loadScript = (url, opts, cb) => {
  // if cached.
  if (!window.requireJsRegistry) {
    window.requireJsRegistry = {}
  }
  const cachedResult = window.requireJsRegistry[url]
  if (cachedResult) {
    //   if (process.env.NODE_ENV !== 'production') {
    //     debug('Cached %s %o', url, cachedResult);
    //   }
    if (cb) {
      cb(cachedResult)
    }
    return cachedResult
  }

  // if not cached.
  const { check, ...restOpts } = opts
  const script = scripts[url] || url

  // if (process.env.NODE_ENV !== 'production') {
  //   debug('load %s', url);
  // }

  loadScriptJs(script, restOpts, () => {
    const ret = hasValue(check)
    if (ret || !check) {
      window.requireJsRegistry[url] = ret
      if (cb) {
        cb(ret)
      }
    } else {
      console.info("Error loading script: %o", script)
    }
  })
}

const hasValue = (check) => {
  if (typeof check === "string") {
    return window[check]
  }
  if (check && check.length === 1) {
    return window[check[0]]
  }
  if (check && check.length === 2) {
    return window[check[0]] && window[check[0]][check[1]]
  }
  return false
}

export const loadD3v3 = (cb) => {
  loadScript("d3v3", { check: "d3" }, cb)
}
